package com.zmwx.club.gateway.filter;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.simpleframework.xml.Order;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author： zmwx
 * @Date： 2024/4/7 21:53
 * @Describe： 登陆拦截
 */
@Slf4j
@Component
public class LoginFilter implements GlobalFilter   {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpRequest.Builder mutate = request.mutate();
            String path = request.getURI().getPath();
            log.info("***********filter.path:{}", path);
            if (path.equals("/user/doLogin") || path.equals("/user/isLogin")) {
                return chain.filter(exchange);
            }
            // StpUtil.searchTokenValue("eda3",  0, -1,true);
            SaRequest request1 = SaHolder.getRequest();
            String token = SaHolder.getRequest().getHeader("satoken");
            String tk = SaHolder.getRequest().getHeader("satoken");

            System.out.println("🍀  token " + token);


            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            String loginId = (String) tokenInfo.getLoginId();
            log.info("***********filter.loginId:{}", loginId);
            if (StringUtils.isEmpty(loginId)) {
                throw new RuntimeException("请检查token");
            }
            mutate.header("loginId", loginId);
            return chain.filter(exchange.mutate().request(mutate.build()).build());
        } catch (Exception e) {
            System.out.println("🍀");
            log.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }

    }


}
